package com.ts.camera2

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.SurfaceTexture
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraCaptureSession
import android.hardware.camera2.CameraCaptureSession.CaptureCallback
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraDevice
import android.hardware.camera2.CameraManager
import android.hardware.camera2.CaptureRequest
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import android.view.Surface
import androidx.core.app.ActivityCompat


class CameraUtil() {

    private var mPreviewBuilder: CaptureRequest.Builder? = null
    var mCameraHandler:Handler?=null
    var cameraDevice:CameraDevice?= null

    var surface: Surface?=null

    private  val TAG = "CameraUtil"
    fun openCamera(mContext: Context,width:Int,height:Int,mSurfaceTexture:Surface?){
        this.surface=mSurfaceTexture;
        val cameraManager =mContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager;

        var cameraId=""
        //获取cameraid
        for (s in cameraManager.cameraIdList) {
//      val characteristics = cameraManager.getCameraCharacteristics(cameraId)
            var characteristics = cameraManager.getCameraCharacteristics(s);
            //获取是前置还是后置摄像头
            var facing = characteristics.get(CameraCharacteristics.LENS_FACING);
            //使用后置摄像头
            if (facing != null && facing == CameraCharacteristics.LENS_FACING_BACK) {
                var map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                if (map != null) {
                    cameraId = s;
                }
            }
        }
        if (ActivityCompat.checkSelfPermission(
                mContext,
                Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            return
        }
        cameraManager.openCamera(cameraId,callback,mCameraHandler)
    }
    fun openCamera(mContext: Context,width:Int,height:Int,mSurfaceTexture:SurfaceTexture?){
        this.surface=Surface(mSurfaceTexture);
         val cameraManager =mContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager;

         var cameraId=""
         //获取cameraid
         for (s in cameraManager.cameraIdList) {
             Log.e(TAG, "cameraIdList$s")
//             val characteristics = cameraManager.getCameraCharacteristics(cameraId)
             var characteristics = cameraManager.getCameraCharacteristics(s);
             //获取是前置还是后置摄像头
             var facing = characteristics.get(CameraCharacteristics.LENS_FACING);
             //使用后置摄像头
             if (facing != null && facing == CameraCharacteristics.LENS_FACING_BACK) {
                 var map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                 if (map != null) {
                     cameraId = s;
                 }
             }


         }
        if (ActivityCompat.checkSelfPermission(
                mContext,
                Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            return
        }
        cameraManager.openCamera(cameraId,callback,mCameraHandler)
     }

    var callback:CameraDevice.StateCallback=object :CameraDevice.StateCallback(){
        override fun onOpened(camera: CameraDevice) {
            Log.e(TAG,"onOpened")
            cameraDevice=camera;
            mPreviewBuilder=camera.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            surface?.let { mPreviewBuilder?.addTarget(it) };

            camera.createCaptureSession(listOf(surface), mStateCallBack, mCameraHandler);

        }

        override fun onDisconnected(camera: CameraDevice) {
            Log.e(TAG,"onDisconnected")
            cameraDevice?.close();
        }

        override fun onError(camera: CameraDevice, error: Int) {
            Log.e(TAG,"onDisconnected"+error)
            cameraDevice?.close();
        }

    }
    private var mPreviewRequest: CaptureRequest? = null
    private var mCaptureSession: CameraCaptureSession? = null
    fun closeCamera() {
        cameraDevice?.close()
    }
    private val mFlashSupported = false
    private var mStateCallBack = object: CameraCaptureSession.StateCallback(){
        override fun onConfigured(session: CameraCaptureSession) {
            if (null == cameraDevice) {
                return
            }
            mCaptureSession = session
            try {
                // 自动变焦是连续的
                mPreviewBuilder?.set<Int>(
                    CaptureRequest.CONTROL_AF_MODE,
                    CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE
                )
                if (mFlashSupported) {
                    mPreviewBuilder?.set<Int>(
                        CaptureRequest.CONTROL_AE_MODE,
                        CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH
                    )
                }
                // 显示相机预览
                mPreviewRequest = mPreviewBuilder?.build()
                mPreviewRequest?.let {
                    mCaptureSession?.setRepeatingRequest(
                        it,
                        listener, mCameraHandler
                    )
                }
            } catch (e: CameraAccessException) {
                e.printStackTrace()
            }


        }

        override fun onConfigureFailed(session: CameraCaptureSession) {
            Log.e(TAG,"onConfigureFailed")
        }

    }
    var listener:CaptureCallback=object :CaptureCallback(){




    }


    init {
        var handlerThread =  HandlerThread("camera")
        handlerThread.start()
        mCameraHandler =  Handler(handlerThread.getLooper())
    }


}